console.log('app start')

var app = new Vue({
  el: '#app',
  data: {
		title: 'PWA-TEST',
		commitList: [],
		headStyle: {
			backgroundColor: 'rgb(0, 188, 212)'
		},
		networkStatus: false,
		serviceWorkerStatus: '',
		SWRegistration: null,
		logo: './static/images/Git_icon_192px.png',
		logoBlack: './static/images/Git_192px.png',
		logoImg: './static/images/Git_icon_192px.png'
	},
	watch: {
		networkStatus (val) {
			console.log(val)
			this.logoImg = val ? this.logo : this.logoBlack
			this.headStyle = val ?
				{ backgroundColor: 'rgb(0, 188, 212)' } : 
				{ backgroundColor: 'rgb(0, 0, 0)' }
		}
	},
	mounted () {
		this.initOffline()
		this.fetchData()
		console.log(typeof this.logo)
		this.handleRegister()
	},
	methods: {
		initOffline () {
			this.updataNetworkStatus()
			document.addEventListener('DOMContentLoaded', event => {
				if(!navigator.onLine) {
					this.updataNetworkStatus()
				}

				window.addEventListener('online', this.updataNetworkStatus, false)
				window.addEventListener('offline', this.updataNetworkStatus, false)
			})
		},

		updataNetworkStatus () {
			if (!navigator.onLine) {
				this.networkStatus = false
				this.$toast('You are now offline...')
			} else {
				this.networkStatus = true
				this.fetchData()
			}
		},

		fetchData () {
			console.log('fetchData')
			let url = 'https://api.github.com/repos/unicodeveloper/resources-i-like/commits'
			fetch(url)
			.then(fetchResponse => {
				return fetchResponse.json()
			})
			.then(response => {
				console.log(response)
				this.commitList = response
			})
		},

		handleRegister () {
			console.log('handleRegister')
			if (!!this.SWRegistration) {
				this.unregisterSW()
			} else {
				this.registerSW()
			}
		},

		registerSW () {
			!this.SWRegistration && navigator.serviceWorker
				.register('../sw.js')
				.then(() => {
					this.updateSWStatus()
					this.$toast('Service Worker Registered')
					console.log('Service Worker Registered')
				})
		},

		unregisterSW () {
			this.SWRegistration && this.SWRegistration.unregister().then(boolean => {
				this.updateSWStatus()
				boolean ? this.$toast('service worker unregistered') : this.$toast('failed to unregister service worker')
			})
		},

		updateSWStatus () {
			if ('serviceWorker' in navigator) {
				navigator.serviceWorker.getRegistration().then(registration => {
					if (!!registration) {
						this.SWRegistration = registration
						this.serviceWorkerStatus = '0'
					} else {
						this.SWRegistration = null
						this.serviceWorkerStatus = '1'
					}
				})
			} else {
				this.serviceWorkerStatus = '2'
			}
		}
	}
})
